﻿using K8.CBB;
using KingerRobot.PCRBW.Dao;
using KingerRobot.PCRMES.Dao;
/**
 * 同步MES信息
 * */
namespace KingerRobot.PCRQuartz;

public class SyncMes
{
    private readonly static object _Lock = new object();

    /// <summary>
    /// 定时同步产品产出信息
    /// </summary>
    public void SyncProduct()
    {
        this.WriteLog($"开始同步钢丝圈信息");
        try
        {
            var mesService = K8.RSF.Client.Create<IMesOrderService>();
            var prodService = K8.RSF.Client.Create<IMesProductService>();
            var mesProductions = mesService.QueryMesProductions();
            if (mesProductions is null || mesProductions.Count==0) return;
  
            lock (_Lock)
            {
                foreach (var wms_product in mesProductions)
                {
                    //if (wms_product.UPDATE_FLAG)
                    {
                        WriteLog($"MESPROD开始添加：{wms_product.PRODUCTION_ID}");
                        MesProduct mesProduct = new MesProduct()
                        {
                            Id = wms_product.PRODUCTION_ID,
                            EquipName = wms_product.EQUIP_NAME,
                            SourceType = wms_product.SOURCE_TYPE,
                            BatchName = wms_product.BATCH_NAME,
                            Status = 0,
                            RFID = "",
                            PartNumber = wms_product.PART_NUMBER,
                            Quantity =decimal.Parse(wms_product.QUANTITY.GetValueOrDefault().ToString()),
                            ProduceTime = wms_product.PRODUCE_TIME,
                            PassFlag = wms_product.PASS_FLAG,
                            CreateTime = wms_product.CREATE_TIME,
                            CreateUser = wms_product.CREATE_USER,
                            InTime = Convert.ToDateTime("1901-01-01"),
                            OutTime = Convert.ToDateTime("1901-01-01"),
                            UpdateTime = wms_product.LAST_MODIFIED_TIME,
                            UpdateUser = wms_product.LAST_MODIFIED_USER,
                            Remarks = wms_product.REMARKS,
                            UpdateFlag = wms_product.UPDATE_FLAG,
                            MPartNumber = wms_product.MPARTNUMBER,
                            MPartRevision = wms_product.MPARTREVISION,
                            StorageNo = wms_product.STORAGE_NO,
                            TraceCode = wms_product.TRACECODE,
                            MaterialDesc = string.Empty,
                            LotNo = wms_product.LOT_NO,
                            ShiftValue = wms_product.SHIFT_VALUE,
                            ClassValue = wms_product.CLASS_VALUE,
                            ExpriationTime = wms_product.EXPIRATION_TIME,
                            innerdiameter =decimal.Parse(wms_product.INNERDIAMETER.GetValueOrDefault().ToString()),
                            PartDesc=wms_product.PART_DESC
                        };
                        this.WriteLog($"钢丝圈产222:{mesProduct.ToJson()}");
                    
                        int result = prodService.SyncMesProduct(mesProduct);
                        this.WriteLog($"钢丝圈产333:{result}");
                        if (result > 0)
                        {
                            this.WriteLog($"开始修改RCVFLAG:{wms_product.PRODUCTION_ID}");
                            i_wms_production mesProducts = new i_wms_production();
                            mesProducts.UPDATE_FLAG = 0;
                            mesProducts.PRODUCTION_ID = wms_product.PRODUCTION_ID;
                            mesService.UpdateMesProduction(mesProducts);
                            this.WriteLog($"修改RCVFLAG完成：{wms_product.PRODUCTION_ID}");
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            WriteLog($"同步钢丝圈信息异常-{ex.ToString()}");
        }
    }
    /// <summary>
    /// 定时同步产品锁定
    /// </summary>
    public void SyncProductLock()
    {
        this.WriteLog($"开始同步钢丝圈状态" );
        try
        {
            lock (this)
            {
                var mesService = K8.RSF.Client.Create<IMesOrderService>();
                var mesLockService = K8.RSF.Client.Create<IMesProductLockService>();
                var lockInfos = mesService.QueryMesLocks();
                if (lockInfos ==null) return;
                foreach (var item in lockInfos)
                {
                    MesLock mesLock = new MesLock()
                    {
                        LockId = item.LOCK_ID,
                        BatchName = item.BATCH_NAME,
                        PartNumber = item.PART_NUMBER,
                        RFID = item.RFID_NO,
                        PassFlag = item.PASS_FLAG,
                        CreateTime = item.CREATE_TIME.GetValueOrDefault(),
                        UpdateTime = item.LAST_MODIFIED_TIME.GetValueOrDefault(),
                        CreateUser = item.CREATE_USER,
                        UpdateUser= item.LAST_MODIFIED_USER,
                        Remarks = item.REMARKS,
                        UpdateFlag = item.UPDATE_FLAG
                    };
                    var result = mesLockService.SnycMesLock(mesLock);
                    if (result > 0)
                    {
                        item.UPDATE_FLAG = 0;
                        item.LAST_MODIFIED_TIME =DateTime.UtcNow;
                        item.LAST_MODIFIED_USER ="wms";
                        mesService.UpdateWmsLock(item);//修改同步标志
                    }
                }
            }
        }
        catch (Exception ex)
        {
            this.WriteLog($"同步钢丝圈状态异常-{ex.ToString()}");
        }

    }

    /// <summary>
    /// 定时同步机台叫料订单
    /// </summary>
    public void SyncOutOrdersInfo()
    {
        lock (this)
        {
            this.WriteLog($"同步MES出库信息");
            //同步MES 钢圈产出信息 
            var mesOrderService = K8.RSF.Client.Create<IMesOrderService>();
            var mesOutOrderService = K8.RSF.Client.Create<IMesOutOrdersService>();
            var wms_order = mesOrderService.QueryMesOrder();
            if (wms_order is null || wms_order.Count == 0) return;
            List<MesOutOrder> list = new List<MesOutOrder>();
            foreach (var item in wms_order)
            {
                MesOutOrder order = new MesOutOrder()
                {
                    Id = item.LIST_NO,
                    PartNumber = item.PART_NUMBER,
                    Grade = item.GRADE,
                    RequireCount = string.IsNullOrEmpty(item.REQUIRE_QTY.ToString()) ? 0 : decimal.Parse(item.REQUIRE_QTY.ToString()),
                    OrderType = 1,
                    ActionCount = string.IsNullOrEmpty(item.ACT_QTY.ToString()) ? 0 : decimal.Parse(item.ACT_QTY.ToString()),
                    ShipCount = string.IsNullOrEmpty(item.SHIP_QTY.ToString()) ? 0 : decimal.Parse(item.SHIP_QTY.ToString()),
                    StopFlag = item.STOP_FLAG,
                    ErrorFlag = item.ERR_FLAG,
                    Remarks = item.REMARKS,
                    BatchName = item.BATCH_NAME,
                    PartClass = item.PART_CLASS,
                    TargetEquip = item.TARGET_EQUIP,
                    CreateTime = item.CREATE_TIME,
                    CreateUser = item.CREATE_USER,
                    UpdateTime =DateTime.Now,// item.LAST_MODIFIED_TIME.GetValueOrDefault()
                    UpdateUser = item.LAST_MODIFIED_USER,
                    UpdateFlag = item.UPDATE_FLAG,
                    ErrorInfo = item.ERR_FLAG,
                    MPartNumber = item.MPARTNUMBER,
                    MPartRevision = item.MPARTREVISION,
                    TraceCode = item.TRACECODE,
                    AreaName = item.AREA_NAME,
                    Innerdiameter = item.Innerdiameter
                };
                int result = mesOutOrderService.SyncMesOutOrders(order);
                if (result > 0)
                {
                    item.LAST_MODIFIED_TIME = DateTime.UtcNow;
                    item.LAST_MODIFIED_USER = "wms";
                    result = mesOrderService.UpdateWmsOrder(item);
                    if (result > 0)
                    {
                        this.WriteLog($"同步MES出库信息结束!");
                    }

                }
            }
        }
        
    }

    /// <summary>
    /// 定时同步出库完成订单
    /// </summary>
    public void SyncWmsOut()
    {
        lock (this)
        {
            try
            {
                this.WriteLog($"同步MES钢圈出库完成信息");
                //同步MES 钢圈完成信息 
                var mesOutCompletesService = K8.RSF.Client.Create<IMesOutCompletesService>();
                var mesOrderService = K8.RSF.Client.Create<IMesOrderService>();
                var list = mesOutCompletesService.QueryMesOutCompletesList();
                if (list is null || list.Count == 0) return;

                foreach (var item in list)
                {
                    #region 任务完成更新MES
                    i_wms_out iWmsOut = new i_wms_out();
                    iWmsOut.OUT_ID = item.Id;
                    iWmsOut.LIST_NO = item.ListNo;
                    iWmsOut.PART_NUMBER = item.PartNumber;
                    iWmsOut.BATCH_NAME = item.BatchName;
                    iWmsOut.ELOC_NO = item.ElocNo;
                    iWmsOut.RFID_NO = item.RfidNo;
                    iWmsOut.CREATE_TIME = DateTime.Now;
                    iWmsOut.CREATE_USER = "WCS";
                    iWmsOut.LAST_MODIFIED_TIME =DateTime.Now;
                    iWmsOut.LAST_MODIFIED_USER = "WCS";
                    iWmsOut.REMARKS = "WCS";
                    iWmsOut.UPDATE_FLAG = 1;
                    iWmsOut.AREA_NAME = item.area_name;
                    iWmsOut.STORAGE_NO = item.storage_no;
                    iWmsOut.TARGET_EQUIP = "";
                    iWmsOut.OUT_FLAG = item.out_flag;
                    iWmsOut.PRINT_TIME =DateTime.Now;
                    iWmsOut.OUT_TIME = DateTime.Now;
                    iWmsOut.PART_DESC = string.Empty;
                    iWmsOut.LIST_STATUS = 0;
                    iWmsOut.DATA_TYPE = "WCS";
                    iWmsOut.QUANTITY = item.quantity;
                    #endregion
                    int result = mesOrderService.SaveWmsOut(iWmsOut);
                    if (result > 0)
                    {
                        MesOutComplete mesOutComplete = new MesOutComplete();
                        mesOutComplete.Id = item.Id;
                        mesOutComplete.update_flag = 0;

                        mesOutCompletesService.UpdateMesOutCompletesByUpdateFlag(mesOutComplete);//更新状态
                        this.WriteLog($"同步MES钢圈出库完成信息成功!");
                    }
                }
            }
            catch (Exception ex)
            {
                this.WriteLog($"同步MES钢圈出库完成信息异常信息：{ex.Message}");
            }
        }
    }

    /// <summary>
    /// 同步MES产品合格信息
    /// </summary>
    public void SyncCheckInfo()
    {
        lock (this)
        {
            this.WriteLog($"同步MES产品合格信息");
            //同步MES产品合格信息
            var mesOrderService = K8.RSF.Client.Create<IMesOrderService>();
            var mesCheckService = K8.RSF.Client.Create<IMesCheckService>();
            var wmsCheckList = mesOrderService.QueryWmsCheck();
            if (wmsCheckList is null || wmsCheckList.Count == 0) return;

            foreach (var item in wmsCheckList)
            {
                MesCheck _mesCheck = new MesCheck()
                {
                    Id = item.check_id,
                    batch_name = item.batch_name,
                    part_number = item.part_number,
                    rfid_no = item.rfid_no,
                    check_result = item.check_result,
                    pass_flag = item.pass_flag,
                    create_time = item.create_time,
                    create_user = item.create_user,
                    last_modified_time = item.last_modified_time,
                    last_modified_user = item.last_modified_user,
                    remarks = item.remarks,
                    update_flag = item.update_flag,
                    site_name = item.site_name,
                    area_name = item.area_name,
                };
                int result = mesCheckService.SnycMesCheck(_mesCheck);
                if (result > 0)
                {
                    item.last_modified_time = DateTime.UtcNow;
                    item.last_modified_user = "wms";
                    item.update_flag = 0;
                    result = mesOrderService.UpdateWmsCheck(item);
                    if (result > 0)
                    {
                        this.WriteLog($"同步MES检查信息结束!");
                    }
                }
            }
        }
    }

    #region 文件日志（运行需要 Nlog 配置）
    private void WriteLog(string message,bool flag=false)
    {
        if (flag)
        {
            K8.LSF.Client.Log(new K8.LSF.Log { Data = message });
        }
    }
    #endregion
}
